//*************************************************************************************
//* 作    者： zouhunter
//* 创建时间： 2021-10-09 04:42:48
//* 描    述： 

//* ************************************************************************************
using System;
using System.Collections.Generic;

using UnityEngine;

public class BoxColliderViewBehaviour : MonoBehaviour
{
    protected float m_width = 0.02f;
    [SerializeField]
    protected Color m_color = Color.green;
    [SerializeField]
    protected string m_shaderName = "Custom/Additive";
    private Material m_mat;
    private BoxCollider m_boxCollider;
    protected LineRenderer m_lineRender;

    private void OnEnable()
    {
        m_boxCollider = GetComponentInChildren<BoxCollider>();
        if (!m_boxCollider)
        {
            enabled = false;
            return;
        }

        var boxCenter = m_boxCollider.center;
        var size = m_boxCollider.size * 0.5f;

        Shader shader = Shader.Find(m_shaderName);
        m_mat = new Material(shader);
        var points = new Vector3[] {
            new Vector3(-1,1,-1),
            new Vector3(-1,-1,-1),
            new Vector3(-1,-1,1),
            new Vector3(-1,1,1),
            new Vector3(1,1,-1),
            new Vector3(1,-1,-1),
            new Vector3(1,-1,1),
            new Vector3(1,1,1)
        };
        m_lineRender = gameObject.MustComponent<LineRenderer>();
        m_lineRender.material = m_mat;
        m_lineRender.useWorldSpace = false;
        for (int i = 0; i < points.Length; i++)
        {
            var point = points[i];
            point.Scale(size);
            point += boxCenter;
            points[i] = point;
        }
        m_lineRender.startWidth = m_lineRender.endWidth = m_width;
        m_lineRender.startColor = m_lineRender.endColor = m_color;
        m_lineRender.positionCount = points.Length;
        m_lineRender.SetPositions(points);
    }

    public void SetColor(Color color)
    {
        m_color = color;
        if (m_lineRender)
            m_lineRender.startColor = m_lineRender.endColor = color;
    }

    public void Hide()
    {
        if (m_lineRender)
        {
            Destroy(m_lineRender);
        }
        enabled = false;
    }

    internal void Show()
    {
        if (m_lineRender)
            m_lineRender.enabled = true;
        enabled = true;
    }
}